package com.zhihaoliang.room.workers

import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.squareup.moshi.Types
import com.zhihaoliang.room.data.AppDatabase
import com.zhihaoliang.room.data.Plant
import com.zhihaoliang.room.util.log
import com.zhihaoliang.room.utilities.PLANT_DATA_FILENAME
import com.zhihaoliang.room.utilities.moshi
import kotlinx.coroutines.coroutineScope
import okio.buffer
import okio.source

/**
 * @author 支豪亮
 * @date 2023/1/19 15:46
 * @des 用于创建数据库
 */
class SeedDatabaseWorker(
    context: Context, workerParameters: WorkerParameters
) : CoroutineWorker(context, workerParameters) {
    override suspend fun doWork(): Result = coroutineScope {
        try {
            log("doWork")
            val inputStream = applicationContext.assets.open(PLANT_DATA_FILENAME)

            val plantListType = Types.newParameterizedType(List::class.java, Plant::class.java)
            val plantListAdapter = moshi.adapter<List<Plant>>(plantListType)

            val plantList = plantListAdapter.fromJson(inputStream.source().buffer()) ?: emptyList()

            val database = AppDatabase.getInstance(applicationContext)
            database.plantDao().insertAll(plantList)
            Result.success()
        } catch (e: java.lang.Exception) {
            log(e.toString())
            Result.failure()
        }

    }
}
